//
//  ViewController.m
//  SaveForWebView
//
//  Created by 梁家章 on 2017/8/3.
//  Copyright © 2017年 liangjiazhang. All rights reserved.
//

/**
   长按WKWebView上的图片保存到相册
 */



#import "ViewController.h"
#import <WebKit/WebKit.h>

@interface ViewController ()  <UIGestureRecognizerDelegate,NSURLSessionDelegate>


@property (nonatomic, strong) WKWebView  * mWKWebView;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    [self initSetupWebView];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)initSetupWebView {
    
    
    if (!self.mWKWebView ) {
        self.mWKWebView = [[WKWebView alloc]initWithFrame:self.view.bounds];
        [self.view addSubview:self.mWKWebView];
        
        //给UIWebView添加手势
        UILongPressGestureRecognizer* longPressed = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressed:)];
        longPressed.delegate = self;
        [self.mWKWebView addGestureRecognizer:longPressed];
    }
    //
    [self.mWKWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com/"]]];
    
    
    
}



- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    //设置JS
    NSString *inputValueJS = @"document.getElementsByName('input')[0].attributes['value'].value";
    //执行JS
    [webView evaluateJavaScript:inputValueJS completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"value: %@ error: %@", response, error);
    }];
}



#pragma mark -- UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
   // UIActivityTypeAddToReadingList
    
    return YES;
}

- (void)longPressed:(UILongPressGestureRecognizer*)recognizer{
    if (recognizer.state != UIGestureRecognizerStateBegan) {
        return;
    }
    CGPoint touchPoint = [recognizer locationInView:self.mWKWebView];
    NSString *imgURL = [NSString stringWithFormat:@"document.elementFromPoint(%f, %f).src", touchPoint.x, touchPoint.y];
    
    __weak __typeof(self)weakSelf = self;
    
    [self.mWKWebView evaluateJavaScript:imgURL completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        
        
        if (error ==nil ) {
            
             __strong __typeof(weakSelf)strongSelf = weakSelf;
            
            UIAlertController *alertVC =  [UIAlertController alertControllerWithTitle:@" " message:@"你真的要保存图片到相册吗？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [strongSelf saveImageToDiskWithUrl:response];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"不是" style:UIAlertActionStyleDefault handler:nil];
            [alertVC addAction:okAction];
            [alertVC addAction:cancelAction];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
    }];
    
}


- (void)saveImageToDiskWithUrl:(NSString *)string {
    
    
    
//    NSString *urlStr =[NSString stringWithFormat:@"%@", string];
//    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//    NSURL *Url = [NSURL URLWithString:urlStr];
//    
//    // 创建请求
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url];
//    
//    // 创建会话
//    NSURLSession *session = [NSURLSession sharedSession];
//    
//    NSURLSessionDownloadTask *downLoadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        if (!error) {
//            // 下载成功
//            // 注意 location是下载后的临时保存路径, 需要将它移动到需要保存的位置
//            NSError *saveError;
//            // 创建一个自定义存储路径
//            NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//            NSString *savePath = [cachePath stringByAppendingPathComponent:@"fileName"];
//            NSURL *saveURL = [NSURL fileURLWithPath:savePath];
//            
//            // 文件复制到cache路径中
//            [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveURL error:&saveError];
//            if (!saveError) {
//                NSLog(@"保存成功");
//            } else {
//                NSLog(@"error is %@", saveError.localizedDescription);
//            }
//        } else {
//            NSLog(@"error is : %@", error.localizedDescription);
//        }
//    }];
//    // 恢复线程, 启动任务
//    [downLoadTask resume];
    
    
    
    NSURL *url = [NSURL URLWithString:string];
    
    NSURLSessionConfiguration * configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue new]];
    
    NSURLRequest *imgRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
    
    NSURLSessionDownloadTask  *task = [session downloadTaskWithRequest:imgRequest completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            return ;
        }
        NSData * imageData = [NSData dataWithContentsOfURL:location];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            UIImage * image = [UIImage imageWithData:imageData];
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), NULL);
        });
    }];
    [task resume];
}



#pragma mark 保存图片后的回调
- (void)imageSavedToPhotosAlbum:(UIImage*)image
       didFinishSavingWithError:(NSError*)error
                    contextInfo:(id)contextInfo {
    
    NSString*message =@"保存失败";
    if(!error) {
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:@"成功保存到相册" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:nil];
        [alertControl addAction:action];
        [self presentViewController:alertControl animated:YES completion:nil];
    }else{
        message = [error description];
        UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertControl addAction:action];
        [self presentViewController:alertControl animated:YES completion:nil];
    }
}

@end
